package com.h3c.ptability.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.h3c.it.common.misc.lang.Assert;
import com.h3c.ptability.cache.UserCache;
import com.h3c.ptability.dto.eos.UserRoleDTO;
import com.h3c.ptability.entity.PtAllWorker;
import com.h3c.ptability.entity.PtDept;
import com.h3c.ptability.entity.PtRoleUser;
import com.h3c.ptability.mapper.PtAllWorkerMapper;
import com.h3c.ptability.mapper.PtDeptMapper;
import com.h3c.ptability.mapper.PtRoleUserMapper;
import com.h3c.ptability.service.EosAuthService;
import com.h3c.ptability.service.IPtRoleUserService;
import com.h3c.ptability.dto.PtRoleUserDTO;
import com.h3c.ptability.utils.AppBusinessException;
import com.h3c.ptability.utils.InitExampleOrderByUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtRoleUserServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_role_user serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtRoleUserServiceImpl extends ServiceImpl<PtRoleUserMapper, PtRoleUser> implements IPtRoleUserService {

    @Resource
    private PtRoleUserMapper ptRoleUserMapper;

    @Autowired
    private PtAllWorkerMapper ptAllWorkerMapper;


    /**
     * 部门
     */
    @Resource
    private PtDeptMapper ptDeptMapper;

    /**
     * EOS相关接口
     */
    @Resource
    private EosAuthService eosAuthService;


    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtRoleUserDTO> selectFuzzyByDto(PtRoleUserDTO dto) {
        //List<PtRoleUser> list = ptRoleUserMapper.selectByExample(initFuzzyExample(dto));
        List<PtRoleUser> list = ptRoleUserMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtRoleUser.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtRoleUserDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtRoleUserDTO> selectByDto(PtRoleUserDTO dto) {
        //List<PtRoleUser> list = ptRoleUserMapper.selectByExample(initExample(dto));
        List<PtRoleUser> list = ptRoleUserMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto),PtRoleUser.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtRoleUserDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(PtRoleUserDTO dto) {
        if(!StringUtils.hasText(dto.getUserId())){
            throw new AppBusinessException("工号不可为空");
        }
        if(!StringUtils.hasText(dto.getAppId())){
            throw new AppBusinessException("应用编码不可为空");
        }
        if(!StringUtils.hasText(dto.getRoleId())){
            throw new AppBusinessException("角色编码不可为空");
        }
        PtAllWorker worker = ptAllWorkerMapper.selectById(dto.getUserId());
        if(worker == null ){
            throw new AppBusinessException("人员不存在");
        }
        dto.setCreateTime(new Date());
        dto.setCreatorId(UserCache.getLoginUserNameAndId());
        dto.setDomainAccount(worker.getDomainAccount());
        dto.setUserName(worker.getWorkerName());
        dto.setUserStatus(1);
        return ptRoleUserMapper.insert(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleUser.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(PtRoleUserDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
            return ptRoleUserMapper.updatePtRoleUser(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleUser.class));
            //return ptRoleUserMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), PtRoleUser.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(PtRoleUserDTO dto) {
        if(!StringUtils.hasText(dto.getUserId())){
            throw new AppBusinessException("工号不可为空");
        }
        if(!StringUtils.hasText(dto.getAppId())){
            throw new AppBusinessException("应用编码不可为空");
        }
        if(!StringUtils.hasText(dto.getRoleId())){
            throw new AppBusinessException("角色编码不可为空");
        }
        LambdaQueryWrapper<PtRoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PtRoleUser::getAppId,dto.getAppId())
                .eq(PtRoleUser::getRoleId,dto.getRoleId())
                .eq(PtRoleUser::getUserId,dto.getUserId());
        return ptRoleUserMapper.delete(queryWrapper);
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(PtRoleUserDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtRoleUser.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getRoleId() && !"".equals(dto.getRoleId())) {
                criteriaName.andLike("RoleId", "%" + dto.getRoleId() + "%");
            }
            if (null != dto.getUserId() && !"".equals(dto.getUserId())) {
                criteriaName.andLike("UserId", "%" + dto.getUserId() + "%");
            }
            if (null != dto.getCreateTime() && !"".equals(dto.getCreateTime())) {
                criteriaName.andLike("CreateTime", "%" + dto.getCreateTime() + "%");
            }
            if (null != dto.getUserStatus() && !"".equals(dto.getUserStatus())) {
                criteriaName.andLike("UserStatus", "%" + dto.getUserStatus() + "%");
            }
            if (null != dto.getCreatorId() && !"".equals(dto.getCreatorId())) {
                criteriaName.andLike("CreatorId", "%" + dto.getCreatorId() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(PtRoleUserDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtRoleUser.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getRoleId() && !"".equals(dto.getRoleId())) {
                criteriaName.andEqualTo("RoleId", dto.getRoleId());
            }
            if (null != dto.getUserId() && !"".equals(dto.getUserId())) {
                criteriaName.andEqualTo("UserId", dto.getUserId());
            }
            if (null != dto.getCreateTime() && !"".equals(dto.getCreateTime())) {
                criteriaName.andEqualTo("CreateTime", dto.getCreateTime());
            }
            if (null != dto.getUserStatus() && !"".equals(dto.getUserStatus())) {
                criteriaName.andEqualTo("UserStatus", dto.getUserStatus());
            }
            if (null != dto.getCreatorId() && !"".equals(dto.getCreatorId())) {
                criteriaName.andEqualTo("CreatorId", dto.getCreatorId());
            }
        }
        return example;
    }

    @Override
    public  void updateDeptManagerRole(){

        //查询所有生效且主管不为空的部门
        List<PtDept> ptDeptList = ptDeptMapper.selectList(new QueryWrapper<PtDept>().lambda()
                .eq(PtDept::getDeptStatus,1)
                .isNotNull(PtDept::getDeptManagerId)
        );
        List<String> deptOneLeaderAccountList = new ArrayList<>();
        List<String> deptTwoLeaderAccountList = new ArrayList<>();
        List<String> deptThreeLeaderAccountList = new ArrayList<>();
        ptDeptList.forEach(o ->{
            String deptManagerId = o.getDeptManagerId();
            List<String> managerIdList = Arrays.asList(deptManagerId.split(","));
            LambdaQueryWrapper<PtAllWorker> allWorkerQueryWrapper = new QueryWrapper<PtAllWorker>().lambda()
                    .in(PtAllWorker::getWorkerId, managerIdList);
            List<PtAllWorker> allWorkerList = ptAllWorkerMapper.selectList(allWorkerQueryWrapper);
            if (!CollectionUtils.isEmpty(allWorkerList)) {
                List<String> accountList = allWorkerList.stream()
                        .filter(m -> StringUtils.hasText(m.getDomainAccount()))
                        .map(PtAllWorker::getDomainAccount)
                        .distinct().collect(Collectors.toList());
                if (o.getDeptLevel() == 1) {
                    deptOneLeaderAccountList.addAll(accountList);
                } else if (o.getDeptLevel() == 2) {
                    deptTwoLeaderAccountList.addAll(accountList);
                } else if (o.getDeptLevel() == 3) {
                    deptThreeLeaderAccountList.addAll(accountList);
                }
            }
        });
        if(!CollectionUtils.isEmpty(deptOneLeaderAccountList)){
            UserRoleDTO mdyUserRole = new UserRoleDTO();
            mdyUserRole.setAppId("hr-sign");
            mdyUserRole.setRoleCode("deptOneLeader");
            mdyUserRole.setAccountList(deptOneLeaderAccountList);
            mdyUserRole.setRebindUserRole(false);
            String mdyResult = eosAuthService.resetUserRole(mdyUserRole);
        }
        if(!CollectionUtils.isEmpty(deptTwoLeaderAccountList)){
            UserRoleDTO mdyUserRole = new UserRoleDTO();
            mdyUserRole.setAppId("hr-sign");
            mdyUserRole.setRoleCode("deptTwoLeader");
            mdyUserRole.setAccountList(deptTwoLeaderAccountList);
            mdyUserRole.setRebindUserRole(false);
            String mdyResult = eosAuthService.resetUserRole(mdyUserRole);
        }
        if(!CollectionUtils.isEmpty(deptThreeLeaderAccountList)){
            UserRoleDTO mdyUserRole = new UserRoleDTO();
            mdyUserRole.setAppId("hr-sign");
            mdyUserRole.setRoleCode("deptThreeLeader");
            mdyUserRole.setAccountList(deptThreeLeaderAccountList);
            mdyUserRole.setRebindUserRole(false);
            String mdyResult = eosAuthService.resetUserRole(mdyUserRole);
        }
    }
}
